package com.example.websocket.controller;

import com.example.websocket.entity.AddFriendRequest;
import com.example.websocket.entity.Friend;
import com.example.websocket.entity.User;
import com.example.websocket.service.IAddFriendRequestService;
import com.example.websocket.service.IFriendService;
import com.example.websocket.service.impl.AddFriendRequestServiceImpl;
import com.example.websocket.service.impl.FriendServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
public class AddFriendRequestController {

    @Autowired
    IAddFriendRequestService addFriendRequestService;
    @Autowired
    IFriendService friendService;

    @GetMapping("/addFriend/{id}")
    public String addFriend(@PathVariable("id")int id, HttpSession httpSession){
        User user = (User)httpSession.getAttribute("user");
        AddFriendRequest addFriendRequest = new AddFriendRequest();
        addFriendRequest.setUserid(user.getId());
        addFriendRequest.setToUserid(id);
        if(user.getId() == id){
            return "redirect:/space";
        }
        AddFriendRequest addFriendRequest1 = addFriendRequestService.selectByUserAndToUserid(user.getId(), id);
        if(addFriendRequest1 != null){
            return "redirect:/space";
        }
        addFriendRequestService.insert(addFriendRequest);
        return "redirect:/space";
    }

    @GetMapping("/addFriend/received/{id}")
    public String addFriendReceived(@PathVariable("id")int id,HttpSession session){
        User user = (User)session.getAttribute("user");
        Friend friend = new Friend();
        friend.setUserid(id);
        friend.setUserid2(user.getId());
        friend.setCreatetime(new Date());
        friendService.insert(friend);
        AddFriendRequest addFriendRequest = addFriendRequestService.selectByUserAndToUserid(id, user.getId());
        AddFriendRequest addFriendRequest1 = addFriendRequestService.selectByUserAndToUserid(user.getId(), id);
        if(addFriendRequest != null ){
            addFriendRequestService.deleteByPrimaryKey(addFriendRequest.getId());
        }
        if(addFriendRequest1 != null ){
            addFriendRequestService.deleteByPrimaryKey(addFriendRequest1.getId());
        }
        return "redirect:/space"; 
    }
}
